<template>
  <div class="container_box">
    <div class="flex-align-center">
      <iphone-x class="iphone-x" style="background-color: #f6f5f5">
        <div class="phone_box">
          <div class="bottom-nav">
            <div
                v-for="(item, index) in computedNavItems"
                :key="index"
                :class="{
                active: currentTab === index,
                'is-center': item.isCenter
              }"
                class="nav-item"
                @click="switchTab(index)"
            >
              <img
                  :src="getNavIconUrl(item, index)"
                  alt=""
                  class="nav-icon"
              />
              <span v-if="!item.isCenter" v-px-to-rem style="margin-top: 3px;font-size: 11px">{{ item.name }}</span>
            </div>
          </div>
        </div>
      </iphone-x>
    </div>

    <div class="nav_settings">
      <div class="setting_title">
        <div>底部导航设置&nbsp;&nbsp;至少添加2个导航，最多添加5个导航</div>
        <div class="flex-1"/>
        <el-button class="save_btn" type="primary" @click="saveNavSettings">保存标签</el-button>
      </div>
      <div class="nav_settings_theme">
        <div>
          <span>字体未选中颜色</span>
          <el-color-picker v-model="textColor" style="margin-left: 0.9rem"/>
        </div>
        <div style="margin-top:0.6rem ">
          <span>字体选中颜色</span>
          <el-color-picker v-model="activeTextColor" style="margin-left: 0.9rem"/>
        </div>
      </div>

      <div class="nav_settings_scroll">
        <div
            v-for="(item, index) in navItems"
            :key="index"
            class="nav_item_settings"
        >
          <div class="nav_icon_section">
            <div class="icon_upload_group">
              导航图标
              <div>
                <div class="upload_name">未激活图标</div>
                <image-cropper-upload
                    :ref="el => iconRefs[`upload-${index}-default`] = el"
                    :current-img="getIconUrl(item, 0)"
                    :img-height="60"
                    :img-width="60"
                    upload-path="/admin/ui"
                    @select-img="(url) => handleSelectImg(index, 'default', url)"
                />
              </div>
              <div>
                <div class="upload_name">激活图标</div>
                <image-cropper-upload
                    :ref="el => iconRefs[`upload-${index}-selected`] = el"
                    :current-img="getIconUrl(item, 1)"
                    :img-height="60"
                    :img-width="60"
                    upload-path="/admin/ui"
                    @select-img="(url) => handleSelectImg(index, 'selected', url)"
                />
              </div>
            </div>
            <div
                v-if="navItems.length === 3 || navItems.length===5"
                class="center-switch"
            >
              <span class="switch-label">中间按钮</span>
              <el-switch
                  :modelValue="item.isCenter"
                  :disabled="navItems.length > 5"
                  @change="handleCenterChange(item,index)"
              />
            </div>
          </div>
          <div>
            <div class="input_group">
              <span class="section_name">导航名称</span>
              <el-input v-model="item.name" placeholder="请输入导航名称"/>
            </div>

            <div class="input_group">
              <span class="section_name">链接地址</span>
              <mobile-link-select v-model="item.routerPage"/>
            </div>
          </div>
          <div
              class="delete_icon"
              @click="deleteNav(index)"
          >
            <el-icon>
              <Close/>
            </el-icon>
          </div>
        </div>
        <el-button :disabled="navItems.length >= 5" @click="addNav">添加导航</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import ImageCropperUpload from "@/components/Tools/Upload/ImageCropperUpload.vue"
import { Close } from '@element-plus/icons-vue'

const iconRefs = reactive({})
const currentTab = ref(0)
const theme = computed(() => $store.settings.theme)
const textColor = ref('#000000')
const activeTextColor = ref('#007aff')

// 导航数据结构改进，添加临时预览字段
const navItems = ref([
  {
    name: '首页',
    uiUrl: '',
    uiType: 'image',
    routerPage: '',
    tempUrls: null
  },
  {
    name: '我的',
    uiUrl: '',
    uiType: 'image',
    routerPage: '',
    tempUrls: null
  }
])

const computedNavItems = computed(() => {
  if (navItems.value.length !== 3 && navItems.value.length !== 5) return navItems.value
  const newArr = [...navItems.value]
  const centerIndex = navItems.value.findIndex(item => item?.isCenter)
  if (centerIndex === -1) return newArr
  newArr.splice(centerIndex, 1)
  newArr.splice(navItems.value.length / 2, 0, navItems.value[centerIndex])
  return newArr
})
const getList = () => {
  $xl.apis.getUiByType({jointUrl: '/tabbar'}).then(res => {
    console.log(res)
    res.data.forEach((item, index) => {
      if (!item.extra) return
      const extraData = JSON.parse(item.extra)
      item.isCenter = extraData.isCenter || false
      if (index !== 0) return
      textColor.value = extraData.textColor
      activeTextColor.value = extraData.activeTextColor
    })
    navItems.value = res.data
    // 填充两个数据
    for (let i = 0 ; i < 2 - navItems.value.length ; i++) {
      addNav()
    }
  })
}
getList()

// 获取导航图标URL
const getNavIconUrl = (item, index) => {
  const isActive = currentTab.value === index
  const iconIndex = isActive ? 1 : 0
  if (item.tempUrls?.[iconIndex]) {
    return item.tempUrls[iconIndex]
  }
  return item.uiUrl ? item.uiUrl.split(',')[iconIndex] : ''
}

// 获取图标URL
const getIconUrl = (item, index) => {
  if (item.tempUrls && item.tempUrls[index]) {
    return item.tempUrls[index]
  }
  return item.uiUrl ? item.uiUrl.split(',')[index] : ''
}

// 处理图片选择
const handleSelectImg = (index, type, previewUrl) => {
  if (!navItems.value[index].tempUrls) {
    navItems.value[index].tempUrls = ['', '']
  }
  const urlIndex = type === 'default' ? 0 : 1
  navItems.value[index].tempUrls[urlIndex] = previewUrl
}

// 切换底部导航
const switchTab = (index) => {
  currentTab.value = index
}

// 监听导航项数量变化，自动关闭其他项的中间按钮状态
watch(() => navItems.value.length, newVal => newVal !== 3 && newVal !== 5 && navItems.value.forEach(item => item.isCenter = false))


// 设置项为居中按钮
const handleCenterChange = (item, index) => {
  if (navItems.value.length < 3 || navItems.value.length > 5) return $xl.modal.msgWarning('只有在3或5个导航项时才能设置中间按钮！')
  item.isCenter = !item.isCenter
  if (!item.isCenter) return
  // 关闭其它中间按钮状态
  navItems.value.forEach((item, i) => i !== index && (item.isCenter = false))
}

// 添加导航
const addNav = () => {
  if (navItems.value.length >= 5) return $xl.modal.msgWarning('最多只能添加5个导航')
  navItems.value.push({
    name: '',
    uiUrl: '',
    uiType: 'image',
    routerPage: '',
    tempUrls: null,
    isCenter: false
  })
}

// 删除导航
const deleteNav = (index) => {
  if (navItems.value.length <= 2) {
    return $xl.modal.msgWarning('至少要保留2个导航!')
  }
  const item = navItems.value[index]
  if (Boolean(item.id)) $xl.modal.confirm("确定删除该导航吗,将无法撤回？").then(() => deleteRemoteData(item.id, index))
  else navItems.value.splice(index, 1)

}

const deleteRemoteData = (id, index) => {
  $xl.apis.deleteUi({jointUrl: '/' + id}).then(() => {
    $xl.modal.msgSuccess('删除成功！')
    navItems.value.splice(index, 1)
  }).catch(error => $xl.modal.msgError('删除失败' + error.message))
}

// 校验规则
const validations = [
  {field: 'name', message: '名称不能为空', validate: item => !item.name.trim()},
  {
    field: 'uiUrl',
    message: '图标未上传，请确保上传图标',
    validate: item => {
      if (!item.isCenter) {
        console.log(item)
        return !((item.tempUrls && item.tempUrls.length > 1) || (item.uiUrl && item.uiUrl.split(',').length > 1))
      } else return !(item.tempUrls || item.uiUrl)
    }
  },
]


// 保存导航设置
const saveNavSettings = async () => {
  $xl.modal.openLoading()
  for (const validation of validations) {
    // 查找第一个错误项
    const index = navItems.value.findIndex(item => validation.validate(item))
    if (index !== -1) return $xl.modal.msgWarning(`第${ index + 1 }个导航的${ validation.message }`)
  }

  // 处理每个导航项的图片上传
  const uploadResults = await Promise.all(navItems.value.map(async (item, i) => {
    const defaultRef = iconRefs[`upload-${ i }-default`]
    const selectedRef = iconRefs[`upload-${ i }-selected`]
    if (!defaultRef || !selectedRef) throw new Error(`第${ i + 1 }个导航的上传组件引用获取失败`)
    try {
      const defaultUrl = await defaultRef.uploadImage()
      const selectedUrl = await selectedRef.uploadImage()
      const extraData = {}
      if (i === 0) (extraData.textColor = textColor.value) && (extraData.activeTextColor = activeTextColor.value)
      if (item.isCenter) extraData.isCenter = true
      return {
        ...item,
        uiUrl: [defaultUrl, selectedUrl].filter(url => url).join(','),
        tempUrls: undefined,
        isCenter: undefined,
        extra: JSON.stringify(extraData)
      }
    } catch (error) {
      throw new Error(`第${ i + 1 }个导航的图片上传失败：${ error.message }`)
    }
  }))

  $xl.apis.saveOrUpdateUiList({
    type: 'json',
    jointUrl: '/tabbar',
    params: uploadResults
  }).then(() => {
    getList()
    $xl.modal.closeLoading()
    $xl.modal.msgSuccess('保存成功！')
  })
}
</script>

<style lang="scss" scoped>
.container_box {
  min-height: 100%;
  display: flex;

  .iphone-x {
    margin: 0 60px;
  }

  .phone_box {
    width: 100%;
    height: 100%;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;

    .bottom-nav {
      height: 70px;
      background: #fff;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .nav-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        flex: 1;
        height: 100%;
        cursor: pointer;

        transition: color 0.3s ease;
        color: v-bind(textColor);

        &.active {
          color: v-bind(activeTextColor);
        }

        .nav-icon {
          width: 26px;
          height: 26px;
          object-fit: contain;
        }

        &.is-center {
          transform: translateY(-10px);

          .nav-icon {
            width: 60px;
            height: 60px;
            padding: 8px;
            background: #fff;
            border-radius: 50%;
            box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
          }
        }
      }
    }
  }

  .nav_settings {
    flex: 1;
    display: flex;
    flex-direction: column;
    position: relative;

    .setting_title {
      display: flex;
      align-items: center;
      height: 25px;
      font-size: 16px;

      &::before {
        content: "";
        display: inline-block;
        width: 5px;
        height: 100%;
        margin-right: 10px;
        background-color: v-bind(theme);
      }
    }

    .nav_settings_theme {
      margin: 10px 0;
      padding: 7px 20px;
      background: #f8f9fa;
    }

    .nav_settings_scroll {
      position: absolute;
      width: 100%;
      overflow-y: auto;
      height: calc(100% - 120px - 20px);
      top: 120px;

      margin-bottom: 20px;
      border: 1px solid #E6E6E6;
      border-radius: 6px;
      margin-top: 13px;
      padding-left: 15px;
      padding-bottom: 70px;
    }

    .nav_item_settings {
      margin: 15px 0;
      background: #f8f9fa;
      padding: 20px;
      border-radius: 8px;
      position: relative;
      width: 600px;

      .nav_icon_section {
        margin-bottom: 20px;
        display: flex;
        justify-content: space-between;

        .icon_upload_group {
          margin-left: 6px;
          display: flex;
          gap: 12px;

          .upload_name {
            display: block;
            margin-bottom: 8px;
            color: #666;
            font-size: 14px;
          }
        }

        .switch-label {
          margin-right: 10px;
        }
      }

      .input_group {
        display: flex;
        margin-bottom: 15px;

        .section_name {
          min-width: 80px;
          font-size: 16px;
          line-height: 36px;
        }
      }


      .delete_icon {
        position: absolute;
        transition: opacity 0.21s ease-in-out;
        opacity: 0;
        top: -8px;
        right: -8px;
        width: 16px;
        height: 16px;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        .el-icon {
          font-size: 14px;
          color: #fff;
        }
      }

      &:hover .delete_icon {
        opacity: 1;
      }
    }
  }
}
</style>
